package handler

import (
	"ctrl-sys/cache"
	"ctrl-sys/model"
	"ctrl-sys/pkg"
	"encoding/json"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段为空",
		})
		return
	}

	var u model.User
	err := model.DB.Find(&u).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	}

	if u.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return

}

func List(c *gin.Context) {
	var Role []model.Role

	redis_list_sys := "redis_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_sys).Result()
	if result == "" {
		model.DB.Find(&Role)
		jsonData, _ := json.Marshal(Role)
		cache.Rdb.Set(cache.Ctx, redis_list_sys, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &Role)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": Role,
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var Role model.Role

	redis_detail_sys := "redis_detail_id" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_sys).Result()
	if result == "" {
		model.DB.Where("id = ?", id).Find(&Role)
		jsonData, _ := json.Marshal(Role)
		cache.Rdb.Set(cache.Ctx, redis_detail_sys, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &Role)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": Role,
	})
	return

}
